<?php

namespace App\Repositories;

use App\Enums\RedisKeyEnum;
use App\Services\Tools\RedisService;
use Carbon\Carbon;

class RankingRepository
{
    //获取财富和魅力榜
    public function getRichOrCharmRankingList($params = [])
    {
        $rankType = $params['rank_type'] ?? 1; //1财富榜，2魅力榜
        $dateTag = $params['date_tag'] ?? 1; //1：日榜，2：周榜，3：月榜，1_1：昨日，2_1：上周，3_1：上月
        $nickname = $params['nickname'] ?? '';
        $userCode = $params['user_code'] ?? 0;
        $page = $params['page'] ?? 1;
        $pageSize = $params['page_size'] ?? 10;

        $dateTag = explode('_', $dateTag);

        //拼装redis key
        $rankTypeKey = $rankType == 1 ? 'rich' : 'charm';
        if ($dateTag[0] == 1) {
            $dateKey = 'day';
            $dateFormat = 'Ymd';
        } else if ($dateTag[0] == 2) {
            $dateKey = 'week';
            $dateFormat = 'oW';
        } else {
            $dateKey = 'month';
            $dateFormat = 'Ym';
        }
        $date = date($dateFormat);
        if (isset($dateTag[1])) {
            $date = date($dateFormat, strtotime("$date -$dateTag[1] $dateKey"));
        }
        $redisKey = sprintf(RedisKeyEnum::RICH_CHARM_RANKING_LIST, $rankTypeKey, $dateKey, $date);

        $where = [];
        if ($nickname) {
            $where[] = ['nickname', 'like', "%$nickname%"];
        }
        if ($userCode) {
            $where[] = ['user_code', '=', $userCode];
        }

        //查询数据
        if ($where) {
            $list = [];
            $total = 0;
            $userId = app('model_user_data')->where($where)->value('user_id');
            if ($userId) {
                $score = app('redis')->zscore($redisKey, $userId);
                if ($score !== null) {
                    $list = [$userId => $score];
                    $total = 1;
                }
            }
        } else {
            $startIndex = ($page - 1) * $pageSize;
            $endIndex = $startIndex + $pageSize - 1;
            $list = app('redis')->zrevrange($redisKey, $startIndex, $endIndex, 'WITHSCORES');
            $total = app('redis')->zcard($redisKey);
        }

        //追加查询数据
        //用户数据
        $userIds = array_keys($list);
        $userDatas = app('model_user_data')->getDataWithUserIdMap($userIds);
        //用户公会数据
        $societyDatabase = config('database.connections.mysql_sociaty.database');
        $userSociety = app('model_sc_sociaty_user')->from('sc_sociaty_user as su')
            ->leftJoin($societyDatabase . '.sc_sociaty as s', 'su.sociaty_id', '=', 's.id')
            ->select('su.user_id', 's.sociaty_no')
            ->whereIn('su.user_id', $userIds)
            ->pluck('sociaty_no', 'user_id')->toArray();

        $data = [];
        foreach ($list as $userId => $score) {
            $elem = ['value' => $score];
            if (isset($userDatas[$userId])) {
                $elem['user_code'] = $userDatas[$userId]['user_code'];
                $elem['nickname'] = $userDatas[$userId]['nickname'];
            } else {
                $elem['user_code'] = '';
                $elem['nickname'] = '';
            }
            $elem['society_no'] = $userSociety[$userId] ?? '';
            $elem['rank'] = app('redis')->zrevrank($redisKey, $userId) + 1;
            $data[] = $elem;
        }
        return ['data' => $data, 'total' => $total, 'page' => $page, 'page_size' => $pageSize];
    }

    /**
     * 获取距离上一名差值
     *
     * @param  array  $arr
     * @return array
     */
    private function getLastSub(array $arr)
    {
        $lastSubArr = [];
        for ($i = 0; $i < count($arr); $i++) {
            if ($i != 0) {
                $lastSubArr[$i]['num'] = $arr[$i - 1] - $arr[$i];
                $lastSubArr[$i]['num_format'] = numberFormat($arr[$i - 1] - $arr[$i]);
            } else {
                $lastSubArr[$i]['num'] = $arr[$i];
                $lastSubArr[$i]['num_format'] = numberFormat($arr[$i]);
            }
        }

        return $lastSubArr;
    }

}
